package com.friday.bo.impl;

import java.sql.Date;
import java.util.Calendar;

import com.friday.bo.WorkDayBo;
import com.friday.dao.WorkDayDao;
import com.friday.dao.impl.WorkDayDaoImpl;
import com.friday.po.WorkDay;

public class WorkDayBoImpl implements WorkDayBo {

	@Override
	public int FillWorkDayTable() throws Exception{
		
		Calendar calendar = Calendar.getInstance();
		Date date = new Date(calendar.get(Calendar.YEAR)-1900, calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));
		
		WorkDayDao workDayDao = new WorkDayDaoImpl();
		
		WorkDay wd = workDayDao.queryDayByDate(date);
		
		if (wd == null) {
			Calendar calStart = Calendar.getInstance();
			calStart.set(calendar.get(Calendar.YEAR), 0, 1);
			
			Calendar calEnd = Calendar.getInstance();
			calEnd.set(calendar.get(Calendar.YEAR)+1, 0, 1);
			
			while(calStart.before(calEnd)) {
				String state;
				if (calStart.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calStart.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
					state = "rest";
				}
				else {
					state = "work";
				}
				
				Date d = new Date(calStart.get(Calendar.YEAR)-1900, calStart.get(Calendar.MONTH), calStart.get(Calendar.DATE));

				workDayDao.insertWorkDay(new WorkDay(d, state));
				
				calStart.add(Calendar.DAY_OF_YEAR, 1);
			}
		}
		
		return 1;
	}

	@Override
	public int ChangeWorkDayState(Date date, String state) throws Exception {
		int ret = 0;
		
		WorkDayDao workDayDao = new WorkDayDaoImpl();
		
		WorkDay workDay = workDayDao.queryDayByDate(date);
		
		if(workDay != null) {
			workDay.setState(state);
			ret = workDayDao.updateWorkDay(workDay);
		}
		
		return ret;
	}

}
